'use client';

// 仪表盘页面
// REF: API-USER-0042@v1.0

import React, { useEffect, useState } from 'react';
import {
  FolderOpen,
  FileText,
  Share2,
  Trash2,
  Upload,
  Download,
  Users,
  HardDrive,
  Activity,
  TrendingUp
} from 'lucide-react';

import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Separator } from '@/components/ui/separator';
import { useAuth } from '@/contexts/AuthContext';
import { driveApi } from '@/services/api';

interface StorageStats {
  total: number;
  used: number;
  available: number;
  files: number;
  folders: number;
}

interface QuickAction {
  title: string;
  description: string;
  icon: React.ComponentType<{ className?: string }>;
  href: string;
  color: string;
}

const quickActions: QuickAction[] = [
  {
    title: '上传文件',
    description: '上传新文件到云盘',
    icon: Upload,
    href: '/upload',
    color: 'bg-blue-500'
  },
  {
    title: '新建文件夹',
    description: '创建新的文件夹',
    icon: FolderOpen,
    href: '/files?action=new-folder',
    color: 'bg-green-500'
  },
  {
    title: '共享管理',
    description: '管理共享文件',
    icon: Share2,
    href: '/shared',
    color: 'bg-purple-500'
  },
  {
    title: '回收站',
    description: '查看已删除文件',
    icon: Trash2,
    href: '/trash',
    color: 'bg-red-500'
  }
];

function formatBytes(bytes: number): string {
  if (bytes === 0) return '0 Bytes';
  const k = 1024;
  const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

export default function DashboardPage() {
  const { user, isAdmin } = useAuth();
  const [storageStats, setStorageStats] = useState<StorageStats | null>(null);
  const [recentFiles, setRecentFiles] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const loadDashboardData = async () => {
      try {
        const [storageResponse, filesResponse] = await Promise.all([
          driveApi.getStorageStats(),
          driveApi.getFiles()
        ]);

        if (storageResponse.success) {
          setStorageStats(storageResponse.data);
        }

        if (filesResponse.success) {
          // 获取最近的文件（模拟数据）
          setRecentFiles(filesResponse.data.files.slice(0, 5));
        }
      } catch (error) {
        console.error('加载仪表盘数据失败:', error);
      } finally {
        setLoading(false);
      }
    };

    loadDashboardData();
  }, []);

  if (loading) {
    return (
      <div className="p-6">
        <div className="animate-pulse space-y-6">
          <div className="h-8 bg-gray-200 rounded w-1/4"></div>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
            {[...Array(4)].map((_, i) => (
              <div key={i} className="h-32 bg-gray-200 rounded"></div>
            ))}
          </div>
        </div>
      </div>
    );
  }

  const usagePercentage = storageStats ? (storageStats.used / storageStats.total) * 100 : 0;

  return (
    <div className="p-6 space-y-6">
      {/* 页面标题 */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold text-gray-900">
            欢迎回来，{user?.username}！
          </h1>
          <p className="text-gray-600 mt-1">
            这里是您的云盘管理中心
          </p>
        </div>
        {isAdmin && (
          <Badge variant="secondary" className="px-3 py-1">
            <Users className="h-4 w-4 mr-1" />
            管理员
          </Badge>
        )}
      </div>

      {/* 统计卡片 */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">总文件数</CardTitle>
            <FileText className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{storageStats?.files || 0}</div>
            <p className="text-xs text-muted-foreground">
              包含 {storageStats?.folders || 0} 个文件夹
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">存储使用</CardTitle>
            <HardDrive className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {storageStats ? formatBytes(storageStats.used) : '0 GB'}
            </div>
            <p className="text-xs text-muted-foreground">
              共 {storageStats ? formatBytes(storageStats.total) : '100 GB'}
            </p>
            <div className="mt-2 w-full bg-gray-200 rounded-full h-2">
              <div 
                className="bg-blue-600 h-2 rounded-full transition-all" 
                style={{ width: `${Math.min(usagePercentage, 100)}%` }}
              />
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">今日上传</CardTitle>
            <Upload className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">12</div>
            <p className="text-xs text-muted-foreground">
              <span className="text-green-600">+2.5%</span> 较昨日
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">今日下载</CardTitle>
            <Download className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">28</div>
            <p className="text-xs text-muted-foreground">
              <span className="text-green-600">+12.3%</span> 较昨日
            </p>
          </CardContent>
        </Card>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* 快速操作 */}
        <Card className="lg:col-span-1">
          <CardHeader>
            <CardTitle>快速操作</CardTitle>
            <CardDescription>常用功能快速入口</CardDescription>
          </CardHeader>
          <CardContent className="space-y-3">
            {quickActions.map((action, index) => {
              const Icon = action.icon;
              return (
                <Button
                  key={index}
                  variant="ghost"
                  className="w-full justify-start h-auto p-3"
                  asChild
                >
                  <a href={action.href}>
                    <div className={`p-2 rounded-md ${action.color} mr-3`}>
                      <Icon className="h-4 w-4 text-white" />
                    </div>
                    <div className="text-left">
                      <p className="font-medium">{action.title}</p>
                      <p className="text-sm text-gray-500">{action.description}</p>
                    </div>
                  </a>
                </Button>
              );
            })}
          </CardContent>
        </Card>

        {/* 最近文件 */}
        <Card className="lg:col-span-2">
          <CardHeader>
            <CardTitle>最近文件</CardTitle>
            <CardDescription>您最近访问的文件</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="space-y-3">
              {recentFiles.map((file, index) => (
                <div key={index} className="flex items-center justify-between p-3 hover:bg-gray-50 rounded-lg">
                  <div className="flex items-center gap-3">
                    <div className="p-2 bg-blue-100 rounded-lg">
                      {file.type === 'folder' ? (
                        <FolderOpen className="h-4 w-4 text-blue-600" />
                      ) : (
                        <FileText className="h-4 w-4 text-blue-600" />
                      )}
                    </div>
                    <div>
                      <p className="font-medium">{file.name}</p>
                      <p className="text-sm text-gray-500">
                        {file.type === 'folder' ? '文件夹' : formatBytes(file.size || 0)} • 
                        {typeof window !== 'undefined' ? new Date(file.modified).toLocaleDateString() : new Date(file.modified).toISOString().split('T')[0]}
                      </p>
                    </div>
                  </div>
                  <div className="flex items-center gap-2">
                    {file.shared && (
                      <Badge variant="outline" className="text-xs">
                        <Share2 className="h-3 w-3 mr-1" />
                        共享
                      </Badge>
                    )}
                    <Button variant="ghost" size="sm">
                      打开
                    </Button>
                  </div>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}